<template>
  <div class="zrUpLoad">
    <!-- 新增编辑状态 -->
    <template v-if="type === 'file'">
      <div v-if="!look && !hideUpload" class="w-100 d-flex j-start">
        <el-form v-if="!isdarg" :inline="true" size="small" class="w-100">
          <el-form-item label="" class="mr-0">
            <div class="d-flex">
              <el-input v-model="upLoadFileName" placeholder="请选择附件" disabled class="mr-1" />
              <el-upload
                :action="''"
                :accept="type === 'file' ? '.pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .png, .jpg, .jpeg, .gif, .mp3, .mp4, .MP3, .MP4' : '.png, .jpg, .jpeg, .gif'"
                :auto-upload="true"
                :file-list.sync="fileLists"
                :show-file-list="false"
                :http-request="
                  (file) => {
                    submitUpload()
                  }
                "
                :before-upload="beforeUpload"
              >
                <el-button class="disableStatusBox" icon="el-icon-upload" :disabled="disableStatus">{{ btnDes }}</el-button>
              </el-upload>
            </div>
            <div style="font-size: 12px" class="text-danger">{{
              `*只能上传${type === 'file' ? 'pdf/doc/docx/xls/xlsx/ppt/pptx/png/jpg/jpeg/gif/mp3/mp4' : 'png/jpg/jpeg/gif'}文件，且不超过${type === 'file' ? `${size === 50 ? '50MB' : '1GB'}` : '5MB'}，限制最多上传${onlyOne ? 1 : 10}个文件。`
            }}
            </div>
          </el-form-item>
          <el-form-item v-if="showProgress" label="上传进度：">
            <div style="width: 200px; padding-top: 7px;">
              <el-progress :percentage="progressPercent" :status="progressStatus" />
            </div>
          </el-form-item>
        </el-form>
        <el-form v-else>
          <el-upload
            :action="''"
            class="upload-demo"
            drag
            :auto-upload="true"
            :file-list.sync="fileLists"
            :show-file-list="false"
            :accept="type === 'file' ? '.pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .png, .jpg, .jpeg, .gif, .mp3, .mp4, .MP3, .MP4' : '.png, .jpg, .jpeg, .gif'"
            :http-request="
              (file) => {
                submitUpload()
              }
            "
            :before-upload="beforeUpload"
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将文件拖到此处，或<em>单击此区域</em>上传文件</div>
            <div slot="tip" style="font-size: 12px" class="text-danger">{{
              `*只能上传${type === 'file' ? 'pdf/doc/docx/xls/xlsx/ppt/pptx/png/jpg/jpeg/gif/mp3/mp4' : 'png/jpg/jpeg/gif'}文件，且不超过${type === 'file' ? `${size === 50 ? '50MB' : '1GB'}` : '5MB'}，限制最多上传${onlyOne ? 1 : 10}个文件。`
            }}
            </div>
          </el-upload>
        </el-form>
      </div>
      <el-table v-if="type === 'file' && showType === 'table'" class="mb-3" :data="upLoadFileList" style="width: 100%">
        <el-table-column type="index" label="序号" align="center" width="80px" />
        <el-table-column label="附件名称" align="center">
          <template slot-scope="scope">
            <b>{{ scope.row.attachFileName || scope.row.attachName }}</b>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              class="mr-2"
              type="primary"
              plain
              size="small"
              title="下载"
              icon="el-icon-download"
              @click="handleLoad(scope.row.attachUuid)"
            />
            <el-popconfirm
              title="此操作将删除附件，请谨慎操作！是否继续?"
              cancel-button-type="info"
              @confirm="handleRemove(scope.row)"
            >
              <el-button
                v-if="!look"
                slot="reference"
                class="mr-2"
                type="danger"
                plain
                size="small"
                title="删除"
                icon="el-icon-delete"
              />
            </el-popconfirm>
          </template>
        </el-table-column>
        <el-empty slot="empty" description="暂无数据" />
      </el-table>
      <!-- li列表 -->
      <ul v-if="type === 'file' && showType === 'li'" class="w-100">
        <li
          v-for="(item, i) in upLoadFileList"
          :key="i"
          class="ulli"
          style="display: flex; align-items: center; justify-content: space-between"
        >
          <div class="flex-grow-1" style="font-size: 12px; word-break: break-all;">
            {{ item.attachFileName || item.attachName }}
          </div>
          <div class="text-right ml-1" style="width: 110px">
            <el-link
              class="mr-1"
              type="primary"
              size="small"
              icon="el-icon-download"
              @click="handleLoad(item.attachUuid)"
            >下载
            </el-link>
            <el-popconfirm
              title="此操作将删除附件，请谨慎操作！是否继续?"
              cancel-button-type="info"
              @confirm="handleRemove(item)"
            >
              <el-link v-if="!look" slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-link>
            </el-popconfirm>
          </div>
        </li>
      </ul>
    </template>
    <!-- 图片 -->
    <div v-else-if="type === 'images'" class="image-warp">
      <div class="d-flex flex-wrap">
        <div v-for="(file, index) in upLoadFileList" :key="index" class="image-item mb-2">
          <img :src="getPreviewImgUrl(file.attachUuid)" alt="">
          <span class="item-actions">
            <span @click="handlePictureCardPreview(getPreviewImgUrl(file.attachUuid))">
              <i class="el-icon-zoom-in" style="color: #409eff" />
            </span>
            <a :href="getPreviewImgUrl(file.attachUuid)">
              <i class="el-icon-download" style="color: #67c23a" />
            </a>
            <el-popconfirm
              title="此操作将删除附件，请谨慎操作！是否继续?"
              cancel-button-type="info"
              @confirm="handleRemove(file)"
            >
              <span v-if="!look" slot="reference">
                <i class="el-icon-delete" style="color: #f56c6c" />
              </span>
            </el-popconfirm>
          </span>
        </div>
        <el-form v-if="!look && type === 'images'" :inline="true" size="small">
          <el-form-item>
            <el-upload
              v-if="(onlyOne && upLoadFileList.length < 1) || !onlyOne"
              :action="''"
              :accept="type === 'file' ? '.pdf, .doc, .docx,.xls,.xlsx,.pptx,.mp3,.mp4, .MP3, .MP4' : '.png, .jpg, .jpeg, .gif'"
              :auto-upload="true"
              :file-list.sync="fileLists"
              :show-file-list="false"
              :http-request="
                (file) => {
                  submitUpload()
                }
              "
              :before-upload="beforeUpload"
            >
              <div tabindex="0" class="el-upload el-upload--picture-card"><i data-v-30e62f99="" class="el-icon-plus" />
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div style="font-size: 12px" class="text-danger">{{
        `*只能上传${type === 'file' ? 'pdf/doc/docx/xls/xlsx/ppt/pptx/png/jpg/jpeg/gif/mp3/mp4' : 'png/jpg/jpeg/gif'}文件，且不超过${type === 'file' ? `${size === 50 ? `50MB` : `1GB`}` : '5MB'}，限制最多上传${onlyOne ? 1 : 10}个文件。`
      }}
      </div>
    </div>

    <el-dialog :visible.sync="dialogVisible" :modal="false">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
// import { deleteAttachment } from '@/api/common'
import { getToken } from '@/utils/auth'
import { downloadAttachment } from '@/utils'
import { Toast } from 'vant'

export default {
  props: {
    isdarg: {
      type: Boolean, // 拖拽
      default: false
    },
    type: {
      type: String,
      default: 'file' // file 文件   images  图片
    },
    onlyOne: {
      type: Boolean, // 只能上传一个文件
      default: false
    },
    look: {
      type: Boolean, // 是否查看状态
      default: false
    },
    limit: {
      type: Number,
      default: 10
    },
    list: {
      type: Array,
      default() {
        return []
      }
    },
    size: {
      type: Number,
      default: 50
    },
    showType: {
      type: String,
      default: 'li' // table 表格 li list
    },
    btnDes: {
      type: String,
      default: '添加附件'
    },
    lookName: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      disableStatus: false,
      tools: false,
      hideUpload: false,
      fileLists: [],
      fileType: '.pdf, .doc, .docx,.xls,.xlsx,.ppt,.pptx,.png, .jpg, .jpeg, .gif, .mp3, .mp4',
      imageType: 'jpg、png、jpeg、gif',
      upLoadFileName: '',
      actionUrl: `${process.env.VUE_APP_BASE_API}/admin/attachment/addAttachment.do`,
      progressPercent: 0,
      showProgress: false,
      progressStatus: 'warning',
      upLoadFileList: [],
      downloadFile: `${process.env.VUE_APP_BASE_API}/admin/attachment/downloadAttachmentByUUID.do?attachUuid=`,
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  computed: {
    getPreviewImgUrl() {
      return (uuid) => {
        return uuid.includes('downloadAttachmentByUUID.do') ? uuid : `${this.downloadFile}${uuid}`
      }
    }
  },
  watch: {
    list(newVal) {
      this.upLoadFileList = newVal
    },
    upLoadFileList(newVal) {
      this.upLoadFileList.forEach(item => {
        item.attachId = item.attachId || item.fileId
        item.attachName = item.attachName || item.fileName
        item.attachUuid = item.attachUuid || item.fileUrl
      })
      this.hideUpload = this.onlyOne && newVal.length > 0 ? this.onlyOne && newVal.length > 0 : false
    }
  },
  mounted() {
    if (this.list.length > 0) {
      this.upLoadFileList = this.list
    }
  },
  methods: {
    handleExceed(files, fileList) {
      Toast.fail(`最多支持上传${this.onlyOne ? 1 : 10}附件！`)
    },
    // 选择附件
    beforeUpload(newFile) {
      var testmsg = newFile.name.substring(newFile.name.lastIndexOf('.') + 1)
      const state = this.type === 'file' ? this.fileType.indexOf(testmsg) > -1 : this.imageType.indexOf(testmsg) > -1
      const size = this.type === 'file' ? newFile.size / 1024 / 1024 < this.size : newFile.size / 1024 / 1024 < 5
      if (newFile.size === 0) {
        Toast.fail('不能上传空文件')
        return false
      } else if (!state && !this.isdarg) {
        Toast.fail({
          message: this.type === 'file' ? '上传文件只能是pdf/doc/docx/xls/xlsx/ppt/pptx/png/jpg/jpeg/gif格式！' : '上传文件只能是png/jpg/jpeg/gif格式！',
          type: 'warning'
        })
        return false
      } else if (!size) {
        Toast.fail(this.type === 'file' ? `上传文件大小不能超过${this.size}MB！` : '上传文件大小不能超过 5MB！')
        return false
      }
      this.fileLists = []
      this.progressPercent = 0
      this.showProgress = true
      this.progressStatus = 'warning'
      this.upLoadFileName = newFile.name
      this.fileLists.push({
        name: newFile.name,
        url: '',
        file: newFile,
        status: 'ready',
        percentage: 0
      })
    },
    // 上传附件
    submitUpload() {
      this.disableStatus = true
      let readyFile = null
      if (this.fileLists.length === 0) {
        return Toast.fail('请选择附件')
      } else {
        if (this.onlyOne && this.upLoadFileList.length >= 1) {
          this.disableStatus = false
          return Toast.fail('只能上传一个附件')
        } else if (this.upLoadFileList.length >= 10) {
          this.disableStatus = false
          return Toast.fail('限制最多上传10个文件')
        } else {
          for (const file of this.fileLists) {
            if (file.status === 'uploading') {
              this.disableStatus = false
              return Toast.fail('已有文件正在上传')
            }
            if (file.status === 'ready') {
              readyFile = file
            }
          }
        }
      }
      const token = getToken()
      const formdata = new FormData()
      formdata.append('file', readyFile?.file)
      formdata.append('attachDesc', readyFile?.name)
      formdata.append('attachName', readyFile?.name)
      const config = {
        headers: {
          token: token
        },
        onUploadProgress: (progressEvent) => {
          // progressEvent.loaded:已上传文件大小
          // progressEvent.total:被上传文件的总大小
          this.progressPercent = Number(((progressEvent.loaded / progressEvent.total) * 100).toFixed(2))
        }
      }
      this.$axios.post(this.actionUrl, formdata, config).then((res) => {
        const result = res.data
        if (result.status === 0 && result.data) {
          Toast.success('上传成功')
          this.upLoadFileName = ''
          this.fileLists = []
          this.progressStatus = 'success'
          result.data.filetype = this.type
          this.upLoadFileList.push(result.data)
          this.$emit('uploadCallback', result.data)
          if (this.onlyOne && this.upLoadFileList.length > 0) {
            this.hideUpload = true
          }
          setTimeout(() => {
            this.showProgress = false
          }, 3000)
        } else {
          Toast.fail(result.msg)
          this.progressStatus = 'exception'
          setTimeout(() => {
            this.showProgress = false
          }, 3000)
        }
        this.disableStatus = false
      })
    },
    // 预览附件
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url
      this.dialogVisible = true
    },
    // 删除附件
    handleRemove(file) {
      const { attachId } = file
      const index = this.upLoadFileList.findIndex((v) => {
        return v.attachId === attachId
      })
      this.deleteFile(attachId, index)
    },
    handleLoad(val) {
      downloadAttachment({ attachUuid: val })
    },
    async deleteFile(attachId, index) {
      Toast.success('删除成功')
      this.upLoadFileList = this.upLoadFileList.filter((v) => {
        return v.attachId !== attachId
      })
      this.$emit('deleteCallback', attachId)
      if (this.onlyOne && this.upLoadFileList.length === 0) {
        this.hideUpload = false
      }
      // const { status, msg } = await deleteAttachment({ attachId: attachId })
      // if (status === 0) {
      //   Toast.success(msg)
      //   this.upLoadFileList = this.upLoadFileList.filter((v) => {
      //     return v.attachId !== attachId
      //   })
      //   this.$emit('deleteCallback', attachId)
      //   if (this.onlyOne && this.upLoadFileList.length === 0) {
      //     this.hideUpload = false
      //   }
      // } else {
      //   Toast.fail(message: msg)
      // }
    }
  }
}
</script>

<style lang="scss">
.zrUpLoad {
  .el-form {
    .el-form-item {
      margin-bottom: 0;
    }
  }

  .el-upload--picture-card {
    width: 100px;
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .image-warp {
    .image-item {
      width: 120px;
      height: 150px;
      margin-right: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      overflow: hidden;
      flex-direction: column;

      img {
        width: 100%;
        height: 120px;
      }

      .item-actions {
        border: 1px solid #e2e2e2;
        width: 100%;
        height: 30px;
        display: flex;
        justify-content: space-around;
        border-radius: 0 0 3px 3px;

        i {
          cursor: pointer;
          font-size: 18px;
          font-weight: bold;
        }
      }
    }
  }

  .el-dialog__header {
    border-bottom: none !important;
  }

  .ulli {
    transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
    font-size: 14px;
    color: #606266;
    line-height: 32px;
    position: relative;
    box-sizing: border-box;
    border-radius: 4px;
    width: 100%;
    // height: 32px;
  }
}

.el-popover {
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.2);
}

.el-popconfirm {
  .el-popconfirm__action {
    margin-top: 5px;
  }

  .el-button--info {
    background-color: rgba(0, 0, 0, 0);
    border-color: #dcdfe6;
    color: #606266;
  }

  .el-popconfirm__main {
    padding: 10px 20px;
  }
  .el-button--small {
    height: 50px !important;
  }
}
.disableStatusBox {
  height: 0.85rem !important;
  font-size: 0.32rem !important;
  margin-right: 0.2rem;
}
</style>
